package com.zhrenjie04.alex.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.TimeoutException;

import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.Connection;

import com.rabbitmq.client.Channel;

public class AuditLogUtil {

	private static final Logger logger = Logger.getLogger(AuditLogUtil.class);

	public static Object around(ProceedingJoinPoint pjp, CachingConnectionFactory connectionFactory) throws Throwable {
		HashMap<String, Object> msg = new HashMap<String, Object>();
		Object result = pjp.proceed();
		msg.put("result", result);
		Connection connection = connectionFactory.createConnection();
		Channel channel = connection.createChannel(false);
		try {
			channel.basicPublish("AuditLogExchanger", "AuditLogQueue", null, JsonUtil.stringify(msg).getBytes());
			channel.close();
		} catch (IOException | TimeoutException e) {
			logger.error(e);
			throw new RuntimeException(e);
		} finally {
			connection.close();
		}
		return result;
	}
}
